//
//  MYGSelectDoctorVC.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/7.
//

import UIKit
import MJRefresh
class MYGSelectDoctorVC: MYGBaseController {
    var patientModel = MYGPatientImages()
    // MARK: - Property
    private var page = 1
    var indexArray = [String]()
    var doctorids = [Int]()
    var model = [MYGFriendModel]()
    var selectedPhone = ""
    var sortedNameDict = [String:[MYGFriendModel]]()
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc
    private func keyboardWillHide(_ noti:Notification) {
        self.page = 1
        self.model.removeAll()
        refresh()
    }
    // MARK: - UI
    private func configUI() {
        title = "分享"
        view.addSubview(serachBView)
        serachBView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(23)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(35)
        }
        
        serachBView.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(11)
            make.right.equalToSuperview().offset(-11)
            make.top.bottom.equalToSuperview()
        }
       
        
        view.addSubview(sureBtn)
        sureBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(28)
            make.right.equalToSuperview().offset(-28)
            make.height.equalTo(40)
            make.bottom.equalToSuperview().offset(-bottomSafeheight)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(serachBView.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(sureBtn.snp.top).offset(-10)
        }
        
        sureBtn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))

        refresh()
    }
    

    @objc func refresh() {
        MYGLoading.show()
        MMYGNetwork<MYGMessageApi, MYGPageModel<MYGFriendModel>>.request(target:.searchDoctor(kwd: searchTextField.text ?? "", department: "", hospital: "", title: searchTextField.text ?? "",page: self.page)) { [weak self] item in
            MYGLoading.hide()
            guard let `self` = self else {return}
            guard let item = item else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self.model = item.list 
            } else {
                self.model.append(contentsOf: item.list)
            }
            
            if item.page.total <= self.model.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            self.configDataSource()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    @objc func tapShare() {
        var result = [MYGFriendModel]()
        for (_,dic) in self.sortedNameDict.enumerated() {
            let value = dic.value
            for (_,data) in value.enumerated() {
                if data.selected == true {
                    result.append(data)
                }
            }
        }
        doctorids.removeAll()
        var phones = [String]()
        for (_,obj) in result.enumerated() {
            doctorids.append(obj.id)
            phones.append(obj.phone)
        }
        if doctorids.count == 0 {
            MMYGHUD.showToast(text: "请先选择医生")
            return
        }
        if let phone = phones.first {
            selectedPhone = phone
        }
       
        sendMsg()
        
//        showSureShareAlert()
    }
    func showSureShareAlert() {
        self.popup.dialog(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = Bundle.main.loadNibNamed("MYGShareValidityPeriodAlert", owner: nil, options: nil)?.first as! MYGShareValidityPeriodAlert
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: 340, height: 206)
            actionSheet.tapSureCompletion = {[weak self] timeString in
                self?.popup.dismissPopup()
                self?.toSubmit(timeString: timeString)
                self?.sendMsg()
            }
            actionSheet.tapCancelCompletion = {[weak self] in
                self?.popup.dismissPopup()
            }
            return actionSheet
        }
    }
    
    func toSubmit(timeString:String) {
        let valid_startTime = MYGHelp.getCurrentTime()
        var valid_endTime = ""
        if timeString == "七天" {
            valid_endTime = MYGHelp.after7Days()
        }else if timeString == "1个月" {
            valid_endTime = MYGHelp.after1Month()
        }else if timeString == "3个月" {
            valid_endTime = MYGHelp.after3Month()
        }else if timeString == "1年" {
            valid_endTime = MYGHelp.after1Year()
        }else if timeString == "永久" {
            valid_endTime = ""
        }
        let params = ["patient_id":patientModel.patient_id,
                      "doctor_ids":doctorids,
                      "value":patientModel.value,
                      "name":patientModel.name,
                      "file":patientModel.file,
                      "valid_startTime":valid_startTime,
                      "valid_endTime":valid_endTime] as [String : Any]
        
        MYGLoading.show()
         MYGNetwork<MYGPatientImageApi, MYGEmptyModel>.request(target: .shareExamination(params: params)) {[weak self] item in
             MMYGHUD.showToast(text:"分享成功")
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: {[weak self] in
                 self?.navigationController?.popViewController(animated: true)
             })
             NotificationCenter.default.post(name: NSNotification.Name("MYGpatientImageListVC_configDataSource"), object: nil)
             MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func sendMsg() {
        let params = ["phone":selectedPhone,
                      "id":patientModel.id,
                     ] as [String : Any]
        
        MYGLoading.show()
         MYGNetwork<MYGPatientImageApi, MYGEmptyModel>.request(target: .sendMsg(params: params)) { item in
             MYGLoading.hide()
             MMYGHUD.showToast(text: "分享成功")
             DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: {[weak self] in
                 self?.navigationController?.popViewController(animated: true)
             })
             NotificationCenter.default.post(name: NSNotification.Name("MYGpatientImageListVC_configDataSource"), object: nil)
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func configDataSource() {
        self.indexArray.removeAll()
        self.sortedNameDict.removeAll()
        for(_,obj) in self.model.enumerated() {
            self.indexArray.append(obj.name.getFirstLetter())
        }
        self.indexArray = self.indexArray.uniqued{$0}
        for (_,obj) in self.indexArray.enumerated() {
            var dataArray = [MYGFriendModel]()
            for(_,data) in self.model.enumerated() {
                if data.name.getFirstLetter() == obj {
                    dataArray.append(data)
                }
            }
            self.sortedNameDict[obj] = dataArray
        }
        self.indexArray = self.indexArray.sorted()
        self.tableView.reloadData()
    }

    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.refresh()
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.refresh()
        })
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: MYGSelectDoctorCell.self)
        return tableView
    }()
    
    lazy var searchTextField: UITextField = {
        let control = UITextField()
        control.textAlignment = .center
        control.placeholder = "搜索"
        control.delegate = self
        control.clearButtonMode = .whileEditing
        control.returnKeyType = .search
        return control
    }()
    
    var serachBView: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F5F5F5")
        control.addCorner(radius: 17.5)
        return control
    }()
    
    lazy var sureBtn:UIButton = {
        let control = UIButton()
        control.setTitle("确认分享", for: .normal)
        control.setTitleColor(.white, for: .normal)
        control.titleLabel?.font = .regular(16)
        control.layer.cornerRadius = 20
        control.layer.masksToBounds = true
        control.addTarget(self, action: #selector(tapShare), for: .touchUpInside)
        return control
    }()
}

extension MYGSelectDoctorVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGSelectDoctorCell", for: indexPath) as! MYGSelectDoctorCell
        if let model = self.sortedNameDict[self.indexArray[indexPath.section]]?[indexPath.row] {
            cell.model = model
        }
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.sortedNameDict.keys.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sortedNameDict[self.indexArray[section]]?.count ?? 0
         
    }
    
      func sectionIndexTitles(for tableView: UITableView) -> [String]? {
          return indexArray
      }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.indexArray[section]
    }

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        for (_,dic) in self.sortedNameDict.enumerated() {
            let value = dic.value
            for(_,obj) in value.enumerated() {
                obj.selected = false
            }
        }
        var tmpdic = self.sortedNameDict
        if  let dataSource = tmpdic[self.indexArray[indexPath.section]] {
            dataSource[indexPath.row].selected = !dataSource[indexPath.row].selected
            tmpdic[self.indexArray[indexPath.section]] = dataSource
        }
        self.sortedNameDict = tmpdic
        self.tableView.reloadData()
    }
}
extension MYGSelectDoctorVC: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        self.page = 1
        self.model.removeAll()
        refresh()
        return true
    }
}
